import React, {Component} from 'react';
import {Input, Button, message, Select} from 'antd';
import {articleType, publish} from '../../api/article'
import Editor from 'for-editor';
import {connect} from 'react-redux'

const {Option} = Select;

class Publish extends Component {
  state = {
    mdValue: '',
    articleTypes: [],
    articleType: '',
    summary: ''
  };


  handleChange = (mdValue) => {
    this.setState({
      mdValue
    })
  };

  componentDidMount() {
    articleType().then(({data}) => {
      this.setState({
        articleTypes: data
      })
    })
  }

  render() {
    let {mdValue, title, articleTypes, articleType, summary} = this.state;
    let {userInfo} = this.props;
    return (
      <div>
        <div style={{width: 1000, margin: '20px auto 0'}}>
          <Input
            style={{width: 400, marginRight: 20}}
            value={title} placeholder={'文章标题'} onChange={(e) => {
            this.setState({
              title: e.target.value
            })
          }}/>
          <Select
            showSearch
            style={{width: 200, marginTop: 10}}
            placeholder="文章分类"
            optionFilterProp="children"
            onChange={(value) => {
              this.setState({
                articleType: value
              })
            }}
          >
            {
              articleTypes.length !== 0 && articleTypes.map(item => <Option key={item} value={item}>{item}</Option>)
            }
          </Select>
          <Input
            style={{marginTop: 10}}
            value={summary} placeholder={'文章摘要'} onChange={(e) => {
            this.setState({
              summary: e.target.value
            })
          }}/>

        </div>

        <Editor
          value={mdValue}
          // addImg={($file) => this.addImg($file)}
          preview={false}
          expand={false}
          height={400}
          style={{width: 1000, margin: '20px auto'}}
          onChange={value => this.handleChange(value)}
        />


        <div style={{width: 1000, margin: '0 auto'}}>
          <Button type={'primary'} onClick={() => {
            publish({
              title,
              summary,
              content: mdValue,
              type: articleType,
              username: userInfo.username,
              avatar: userInfo.avatar,
              uid: userInfo.uid
            }).then(res => {
              message.success(res.msg);
              this.props.history.push('/main/list');
            })
          }}>点击发布</Button>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (userInfoReducer) => {
  return {
    userInfo: userInfoReducer
  }

};


export default connect(mapStateToProps)(Publish);
